package com.example.foodDemo.controller;
import com.example.foodDemo.bean.Comment;
import com.example.foodDemo.bean.Food;
import com.example.foodDemo.dao.CommentDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    CommentDao commentDao;

    /*通过食物id查询评论*/
    @RequestMapping("/findById")
    @ResponseBody
    public Map findByFoodId(@RequestBody Food food) {
        Map<String, Object> map = new HashMap<>();

        List<Comment> find = commentDao.findByFoodId(food.getId());

        if (find != null) {
            map.put("success", true);
            map.put("message", "查询成功");
            map.put("data", find);
        } else {
            map.put("success", false);
            map.put("message", "查询失败");
        }
        return map;
    }

    /*发布评论*/
    @RequestMapping("/add")
    @ResponseBody
    public Map addComment(@RequestBody Comment comment) {
        Map<String, Object> map = new HashMap<>();

        Comment comment1 = commentDao.saveAndFlush(comment);

        if (comment1 != null) {
            map.put("success", true);
            map.put("message", "发表评论成功");
            map.put("data", comment1);
        } else {
            map.put("success", false);
            map.put("message", "发表评论失败");
        }
        return map;
    }

    /*通过id查询评论详情*/
    @RequestMapping("/findone/{id}")
    @ResponseBody
    public Map findCommentById(@PathVariable Integer id) {
        Map<String, Object> map = new HashMap<>();

        Optional<Comment> find = commentDao.findById(id);

        if (!find.isEmpty()) {
            Comment comment1 = find.get();
            map.put("success", true);
            map.put("message", "成功");
            map.put("data", comment1);
        } else {
            map.put("success", false);
            map.put("message", "失败");
        }
        return map;
    }
}


